<?php

require(ROOT . '/controllers/CommonController.class.php');

class BookController extends CommonController {

	public function __construct() {
		parent::__construct(__CLASS__);
		$this->model = new Model('book', $this->db);
	}

	public function indexAction() {
		$this->assign('title', '天行健，君子以自强不息；地势坤，君子以厚德载物。');
		$sql = "select * from book";
		$books = $this->db->query($sql);
		$this->assign('books', $books);
		$this->rend('index');
	}

	public function newAction() {
		$this->rend('new');
	}

	public function insertAction() {
		$this->uploadFile($_FILES['cover']);

		$data = array(
			'cover' => $_FILES['cover']['name'],
			'name' => requestPost('name'),
			'author' => requestPost('author'),
			'page' => requestPost('page'),
			'created_at' => time()
		);

		if ($this->model->insert($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('book/index'));
	}

	public function editAction($segments) {
		$id = intval($segments[0]);

		$record = $this->model->find($id);

		$this->assign('record', $record);

		$this->rend('edit');
	}

	public function updateAction() {
		$id = intval(requestPost('id'));

		if (!($record = $this->model->find($id))) {
			echo 'not exsits!';
			exit();
		}

		$data = array(
			'id' => $id,
			'name' => requestPost('name'),
			'author' => requestPost('author'),
			'page' => requestPost('page')
		);

		if ($_FILES['cover']['error'] == 0) {
			$path = ROOT . '/assets/upload/' . $record['cover'];
			if (file_exists($path)) {
				unlink($path);
			}

			$this->uploadFile($_FILES['cover']);

			$data['cover'] = $_FILES['cover']['name'];
		}

		if ($this->model->update($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('book/index'));
	}

	public function deleteAction($segments) {
		$id = intval($segments[0]);

		$record = $this->model->find($id);

		if ($this->model->delete($id)) {
			$imagePath = ROOT . '/assets/upload/' . $record['cover'];
			if (file_exists($imagePath)) {
				unlink($imagePath);
			}
			setFlash('success', 'delete successful');
		} else {
			setFlash('error', 'delete error');
		}

		redirect(url('book/index'));
	}

	private function uploadFile($file) {
		if ($file['error'] != 0) {
			die('upload file failed! ' . $file['error']);
		}

		if ($file['size'] > 1024 * 1024 * 2) {
			die('upload file is too big! ');
		}

		if (!move_uploaded_file($file['tmp_name'], ROOT . '/assets/upload/' . $file['name'])) {
			die('move file failed!');
		}
	}

}